﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FreesenseSubAIS.Core
{
    public class Lights
    {
        System.IO.Ports.SerialPort serialPort1;
        StringBuilder cmd = new StringBuilder();
        private static byte address = 0;
        /// <summary>
        /// 侧光源
        /// </summary>
        /// <param name="comStr"></param>
        public Lights(string comStr)
        {
            try
            {
                serialPort1 = new System.IO.Ports.SerialPort(comStr);
                serialPort1.BaudRate = 9600;
                serialPort1.DataBits = 8;
                serialPort1.WriteTimeout = 3000;
                serialPort1.StopBits = System.IO.Ports.StopBits.One;
                serialPort1.Open();
                Sendcmd(CmdItem.close, 0);
            }
            catch (Exception ex)
            {
                BpjbCommon.Net.Core.BpEventHandler.ErrHandler(string.Format("错误消息：光源串口 {0} 连接失败！\r\n解决方法:\r\n1.检查设备是否运行正常。\r\n2.检查通信串口是否配置正确。\n", comStr) + ex.Message, BpjbCommon.Net.Core.ErrType.Warning);
            }
        }

        public void Dispose()
        {
            if (serialPort1 != null && serialPort1.IsOpen)
            {
                serialPort1.Close();
                serialPort1 = null;
            }
        }
        private void SendCMD(string cmd)
        {
            if (serialPort1 != null && serialPort1.IsOpen)
            {
                serialPort1.DiscardInBuffer();
                serialPort1.Write(cmd);
            }
        }
        /// <summary>
        /// 操作指令
        /// </summary>
        /// <param name="mode">类别</param>
        /// <param name="intensity">参数</param>
        public void Sendcmd(CmdItem mode, byte intensity)
        {
            cmd = new StringBuilder();
            cmd.Append("$");
            cmd.Append(mode.GetHashCode());
            cmd.Append("1");
            cmd.Append(intensity.ToString("X").PadLeft(3, '0'));
            char[] byt = cmd.ToString().ToCharArray();
            byte xorData = (byte)byt[0];
            for (int i = 1; i < byt.Count(); i++)
            {
                xorData = (byte)(xorData ^ (byte)byt[i]);
            }
            cmd.Append(int.Parse(xorData.ToString()).ToString("X").PadLeft(2, '0'));
            SendCMD(cmd.ToString());
        }
    }
    public enum CmdItem
    {
        //空
        none = 0,
        open = 1,
        close = 2,
        modify = 3,
        getintensity = 4
    }
}
